<template>
  <div
    :id="echartId"
    ref="echarts"
    style="width:100%;height:100%" />
</template>
<script>

  import echarts from 'echarts/lib/echarts'
  require('echarts/lib/chart/line') // 按需导入折线组件
  require('echarts/lib/chart/bar') // 按需导入折线组件
  require('echarts/lib/chart/pie') // 饼图
  require('echarts/lib/chart/effectScatter') // 拐点出闪烁，高亮
  require('echarts/lib/component/tooltip') // 提示组件
  require('echarts/lib/component/legend') // 图例组件
  // require('echarts/lib/component/markPoint') // 标注组件
  import 'echarts/lib/component/title'// 标题组件

  export default {
    name: 'Echarts',
    props: {
      echartId: {
        type: [String, Number],
        default: () => Date.now() + Math.floor((Math.random() + 1) * 100) + ''
      },
      chartData: {
        type: Object,
        default: () => { }
      },
      hoverHandler: {
        type: Function,
        default: null
      }
    },
    data() {
      return {
        echarts: null
      }
    },
    watch: {
      chartData: function() {
        if (this.echarts) {
          this.draw()
        }
      }
    },
    mounted() {
      this.initEchart()
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleWindowResize)
      this.echarts = null
    },
    methods: {
      initEchart() {
        this.echarts = echarts.init(document.getElementById(this.echartId))
        window.addEventListener('resize', this.handleWindowResize)
        this.draw()
        // 是否注册hover事件
        if (this.hoverHandler) {
          this.bindHoverEvent()
        }
      },
      bindHoverEvent() {
        this.echarts.on('mouseover', (params) => {
          this.hoverHandler instanceof Function && this.hoverHandler(this.echarts, params)
        })
      },
      handleWindowResize() {
        if (!this.echarts) {
          return
        }
        this.echarts.resize()
      },
      draw() {
        if (!this.chartData.hasData) {
          this.echarts.showLoading({
            text: '暂无数据',
            color: '#ffffff',
            textColor: '#8a8e91',
            showSpinner: false,
            maskColor: 'rgba(255, 255, 255, 0.8)'
          })
          this.echarts.clear()
        } else {
          this.echarts.hideLoading()
          this.echarts.setOption(this.chartData)
        }
      }
    }
  }
</script>
